import request from './request';
import fetchJsonp from 'fetch-jsonp';
import qs from 'qs';

export default {
  get: async (url, data) =>
    request(`${url}${qs.stringify(data) ? `?${qs.stringify(data)}` : ''}`, {
      method: 'get',
    }),
  local: async (url, options) =>
    request(url, {
      method: 'get',
      ...options,
    }),
  post: async (url, data) =>
    request(url, { method: 'post', data }),
  put: async (url, data) =>
    request(url, { method: 'put', data }),
  patch: async (url, data) =>
    request(url, { method: 'patch', data }),
  delete: async (url, data) =>
    request(url, { method: 'delete', data }),
  rpc: async (url, data) =>
    request(url, { method: 'rpc', data }),
  options: async (url) => request(url, { method: 'options' }),
  upload: async (url, data) =>
    request(url, {
      method: 'post',
      data,
      headers: { 'Content-Type': 'multipart/form-data' },
      timeout: 60000,
    }),
  download: async (url, data) =>
    request<Blob>(`${url}${qs.stringify(data) ? `?${qs.stringify(data)}` : ''}`, {
      method: 'get',
      timeout: 30000,
      responseType: 'blob',
      getResponse: true,
    }),
  jsonp: async (url) => {
    const response = await fetchJsonp(url, { jsonpCallback: 'callback' });
    return response.json();
  },
};
